// import { print } from 'graphql/language/printer';

// @ts-nocheck
import { QueryOptions, QueryResult, MutationOptions, FetchResult } from "./types";
import { Link } from "./link";



export interface ClientOptions {
    link: Link
}

export class GraphQLClient {
    private link: Link;

    constructor(options: ClientOptions) {
        this.link = options.link;
        this.query = this.query.bind(this);
        this.mutate = this.mutate.bind(this);
        this.request = this.request.bind(this);
    }

    async query<T>(options: QueryOptions): Promise<QueryResult<T>> {
        let {query, context, fetchPolicy, variables } = options;

        // if (typeof query !== 'string') {
        //     query = print(query);
        // }

        const resp = await this.request(query, variables);
        return resp;
    }

    async mutate<T>(options: MutationOptions<T>): Promise<FetchResult<T>> {
        let {mutation, context, fetchPolicy, variables } = options;

        // if (typeof mutation !== 'string') {
        //     mutation = print(mutation);
        // }

        const resp = await this.request(mutation, variables);
        return resp;
    }

    private async request(query, variables): Promise<{
        data,
        errors
    }> {
        let fetchResult;
        try {
            fetchResult = await this.link.request({
                query,
                variables,
            });

            // console.log('GQL query:', query);
            // console.log('GQL variable: ', variables);
            console.log('GQL FetchResult: ', fetchResult);

        }
        catch (error) {
            console.info(`GraphQL 网络请求错误:`, query, variables);
            const { response } = error;
            if (response && response.data && response.data.errors && response.data.errors.length > 0) {
                // 有错误
                console.info(`GraphQL 请求出现了错误:`, query, variables, response.data.errors);
                // 实际上，我们只抛出第一个错误，其他错误通过控制台和日志输出
                throw new Error(response.data.errors[0].message);
            }
            throw error;
        }

        if (!fetchResult) {
            console.info(`GraphQL 网络请求错误:`, query, variables);
            throw new Error('请求出现了错误，请重试！');
        }

        const { data, errors } = fetchResult;

        if(errors && errors.length > 0){
            // 有错误
            console.info(`GraphQL 请求出现了错误:`, query, variables, errors);
            // 实际上，我们只抛出第一个错误，其他错误通过控制台和日志输出
            throw errors[0];
        }

        return {
            data,
            errors,
        }
    }

    async runQuery(query, variables): Promise<any> {
    }

    // getGraphqlQuery({ query, variables }) {
    //     return `${this.endpoint}?query=${encodeURIComponent(query)}${typeof variables === "object" ? `&variables=${JSON.stringify(variables)}` : ""}`;
    // }
    // runMutation(mutation, variables) {
    //     let { headers = {}, ...otherOptions } = this.fetchOptions;
    //     return fetch(this.endpoint, {
    //         method: "post",
    //         headers: {
    //             Accept: "application/json",
    //             "Content-Type": "application/json",
    //             ...headers
    //         },
    //         ...otherOptions,
    //         body: JSON.stringify({
    //             query: mutation,
    //             variables
    //         })
    //     })
    //         .then(resp => resp.json())
    //         .then(resp => resp.data);
    // }
}
